#!/usr/bin/env bash

# Usage: script/parse-examples [repo_name] [native|wasm]

# Exit immediately if a command exits with a non-zero status.
set -e

# Change directory to project root.
cd "$(dirname "$0")/.."

# Get the repository name
name=$1
repo=examples/$name

# Parse examples in 'native' or 'wasm' mode.
mode=${2:-native}

known_failures=$(cat "script/known-failures-$name.txt")
examples_to_parse=$(
  for example in $(find "$repo" -name '*.hs'); do
    if [[ ! $known_failures == *$example* ]]; then
      echo $example
    fi
  done
)

if [ "$mode" == "native" ]; then
  # Ensure the scanner was recompiled
  tree-sitter test -f 'just compile it' >/dev/null
elif [ "$mode" == "wasm" ]; then
  # Ensure tree-sitter-haskell.wasm was compiled
  make node_modules/web-tree-sitter -s
  make tree-sitter-haskell.wasm -s
fi

start=$(date '+%s.%N')
if [ "$mode" == "native" ]; then
  echo $examples_to_parse | xargs -n 2000 tree-sitter parse -q
elif [ "$mode" == "wasm" ]; then
  echo $examples_to_parse | xargs -n 2000 ./script/tree-sitter-parse.js
fi
end=$(date '+%s.%N')

skipped=$( echo $known_failures | wc -w )
parsed=$( echo $examples_to_parse | wc -w )
total=$((parsed+skipped))
percent=$(bc -l <<< "100*$parsed/$total")
duration=$(bc -l <<< "$end - $start")

printf "Successfully parsed %.2f%% of '$name' in %.4fs (%d of %d files)\n" $percent $duration $parsed $total
